package com.ai.wx.controller;

import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.SortedMap;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.ai.core.constant.GlobalConstant;
import com.ai.core.util.Configure;
import com.ai.wx.entity.History;
import com.ai.wx.entity.MobileMap;
import com.ai.wx.entity.MobileUserInfo;
import com.ai.wx.entity.Product;
import com.ai.wx.entity.ProductOrder;
import com.ai.wx.entity.ProductOrderPre;
import com.ai.wx.exception.FlowMarketException;
import com.ai.wx.handler.RequestHandler;
import com.ai.wx.http.CmccSHHttpPostHelper;
import com.ai.wx.pojo.ProductPrice;
import com.ai.wx.service.HistoryService;
import com.ai.wx.service.MobileMapService;
import com.ai.wx.service.ProductOrderService;
import com.ai.wx.service.ProductService;
import com.ai.wx.util.WeixinUtil;
import com.ai.wx.util.XMLUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SimplePropertyPreFilter;

@Controller
public class WxViewController extends BaseController {

	@Autowired
	private ProductService productService;
	@Autowired
	private HistoryService historyService;

	@Autowired
	private ProductOrderService productOrderService;
	@Autowired
	private MobileMapService mobileMapService;
	@Autowired
	private HttpServletRequest request;
	 

	@RequestMapping(value = "/order")
	public String order(String code, Integer orderState, HttpServletRequest request, HttpServletResponse response) throws UnsupportedEncodingException {
		String openId = getOpenId(request);
		productOrderService.getProdOrderList(openId, orderState, 1, 20);
		return "/order";
	}

	@RequestMapping(value = "/getOrderList")
	@ResponseBody
	public String getOrderList(Integer orderState, int page, int rows, HttpServletRequest request, HttpServletResponse response) throws UnsupportedEncodingException {
		String openId = getOpenId(request);
		List<ProductOrder> productOrderList = productOrderService.getProdOrderList(openId, orderState, page, rows);
		SimplePropertyPreFilter filter = new SimplePropertyPreFilter(ProductOrder.class,"mobile", "dPrice","productName","orderDate", "orderState");
		String responBody = JSON.toJSONString(productOrderList, filter);
		return responBody;
	}

	@RequestMapping(value = "/buy")
	public String buy(String code, HttpServletRequest request, HttpServletResponse response) throws UnsupportedEncodingException {
		String openId = getOpenId(request);
		setJsSign(request);

		List<Product> cmccProducts = productService.getProductsByOperId(GlobalConstant.OPER_ID_CMCC);
		List<Product> cuccProducts = productService.getProductsByOperId(GlobalConstant.OPER_ID_CUCC);
		List<Product> ctccProducts = productService.getProductsByOperId(GlobalConstant.OPER_ID_CTCC);
		request.setAttribute("cmccProducts", JSONObject.toJSONString(cmccProducts));
		request.setAttribute("cuccProducts", JSONObject.toJSONString(cuccProducts));
		request.setAttribute("ctccProducts", JSONObject.toJSONString(ctccProducts));
		
		List<History> historyList=historyService.getHistorysByOpenid(openId);
		if(historyList!=null&&historyList.size()>0){
			request.setAttribute("historyList",historyList);
			request.setAttribute("code",historyList.get(0).getCode());
		}
		return "/buy";
	}

	@RequestMapping(value = "/result")
	public String result(String code, HttpServletRequest request, HttpServletResponse response) throws UnsupportedEncodingException {

		return "/result";
	}

	@RequestMapping(value = "/query")
	public String query(String code, HttpServletRequest request, HttpServletResponse response) throws UnsupportedEncodingException {

		return "/query";
	}

	@RequestMapping(value = "/queryResult")
	public String queryResult(String code, HttpServletRequest request, HttpServletResponse response) throws UnsupportedEncodingException {

		return "/queryResult";
	}

	@RequestMapping(value = "/getMobileMap")
	@ResponseBody
	public MobileMap getMobileMap(String mobileNumber) throws UnsupportedEncodingException {
		if (mobileNumber.length() == 11) {
			mobileNumber = mobileNumber.substring(0, 7);
		}
		MobileMap mobileMap = mobileMapService.getMobileMap(mobileNumber);
		return mobileMap;
	}

	/**
	 * 
	 * @param mobileNumber
	 * @return
	 * @throws UnsupportedEncodingException
	 */
	@RequestMapping(value = "/isSHCmccMobile")
	@ResponseBody
	public boolean isSHCmccMobile(String mobileNumber) throws UnsupportedEncodingException {
		if (mobileNumber.length() == 11) {
			mobileNumber = mobileNumber.substring(0, 7);
		}
		boolean isSHCmccMobile = mobileMapService.isSHCmccMobile(mobileNumber);
		return isSHCmccMobile;
	}

	@RequestMapping(value = "/requestSHCmccSmsCode")
	@ResponseBody
	public String requestSHCmccSmsCode(String mobileNumber) throws Exception {
		String rtnMsg = CmccSHHttpPostHelper.requestSHCmccSmsCode(mobileNumber);
		return rtnMsg;
	}

	@RequestMapping(value = "/doLoginSHCmcc")
	@ResponseBody
	public MobileUserInfo doLoginSHCmcc(String mobileNumber, String smsCode) throws Exception {
		MobileUserInfo rtnObj = CmccSHHttpPostHelper.doLoginSHCmcc(mobileNumber, smsCode);
		request.getSession().setAttribute("mobileUserInfo", rtnObj);
		return rtnObj;
	}
	
	
	@RequestMapping(value = "/getProductPrice")
	@ResponseBody
	public ProductPrice getProductPrice(String productId, String promotionCode) throws FlowMarketException{
		ProductPrice orderPrice = productService.getProdPrice(productId, promotionCode);
		return orderPrice;
	}
	@RequestMapping(value = "/chkPromCode")
	@ResponseBody
	public boolean chkPromCode(String productId, String promotionCode) throws FlowMarketException{
		boolean isValidPromCode = productService.chkPromCode(promotionCode);
		return isValidPromCode;
	}

	@RequestMapping(value = "/getBrandWCPayReqParams")
	@ResponseBody
	public Map<String, String> getBrandWCPayReqParams(String mobileNumber,String productId, String promotionCode,HttpServletResponse response) throws Exception {
		String openId = getOpenId(request);
		//保存用户的历史记录
		historyService.saveHistory(openId,mobileNumber,promotionCode);
		// 获取提交的商品价格
		ProductPrice orderPrice = productService.getProdPrice(productId, promotionCode);
		int iOrderPrice  = orderPrice.getTotal();
		String orderPriceStr = String.valueOf(iOrderPrice);
 		RequestHandler reqHandler = new RequestHandler(request, response);
 		reqHandler.init(Configure.getAppId(), Configure.getAppsecret(), Configure.getPartnerKey());

		Product product =  productService.getProductById(productId);
		// 获取提交的商品名称 
		String productName = product.getProductName();
		String outTradeNo = reqHandler.buildOutTradeNo();
 
		SortedMap<String, String> packageParams = reqHandler.buildPackageMap(openId,orderPriceStr, outTradeNo, productName,request.getRemoteAddr());

 		 
		String postXml = RequestHandler.getRequestXml(packageParams);
		
		String prepayId = WeixinUtil.unifiedorder(postXml);

		// 获取package包
//		String packageValue = reqHandler.genPackage(packageParams); 
		// 设置支付参数
		SortedMap<String, String> signParams =  reqHandler.buildPaySignMap(prepayId);
		
		ProductOrderPre order = new ProductOrderPre();
		order.setMobile(mobileNumber);
		order.setAgentId(orderPrice.getAgentId());
		order.setOutTradeNo(outTradeNo);
		order.setOpenid(openId);
		order.setProductId(productId);
		order.setOrderDate(new Date());
		order.setPrice(orderPrice.getTotal());
		order.setTariff(orderPrice.getTariff());
		order.setDiscount(orderPrice.getDiscount());
		order.setBrokerage(orderPrice.getBrokerage());
		order.setRate(orderPrice.getPromRate());
		order.setPromotionCode(promotionCode);
		order.setOrderState(GlobalConstant.ORDER_STATE_BEGIN);
		order.setPrepayId(prepayId);
		productOrderService.createOrderPre(order);
		
		return signParams;
	}
	
	
	@RequestMapping(value = "/notify")
	@ResponseBody
	public String notify(HttpServletRequest request, HttpServletResponse response) throws Exception {
		 String rtnStr = null;
        InputStream inStream = request.getInputStream();
        ByteArrayOutputStream outSteam = new ByteArrayOutputStream();
        byte[] buffer = new byte[1024];
        int len = 0;
        while ((len = inStream.read(buffer)) != -1) {
            outSteam.write(buffer, 0, len);
        } 
        outSteam.close();
        inStream.close();
        String result  = new String(outSteam.toByteArray(),"utf-8");//获取微信调用我们notify_url的返回信息
        System.out.println(result);
        Map<String,String> map = XMLUtil.doXMLParse(result);
        rtnStr = productOrderService.processWxPayNotify(map, request, response);
//        for(Object keyValue : map.keySet()){
//            System.out.println(keyValue+"="+map.get(keyValue));
//        }
//        if (map.get("result_code").toString().equalsIgnoreCase("SUCCESS")) {
//            //TODO 对数据库的操作  
//        	rtnStr =  RequestHandler.setXML("SUCCESS", "");
//        }else{
//
//        	rtnStr =  RequestHandler.setXML("FAIL", "");
//        }
		System.out.println(rtnStr);
		return rtnStr;
	}

	
	

	
 
}
